package cn.edu.tju.elm.controller;

import cn.edu.tju.elm.model.WalletRule;
import cn.edu.tju.elm.repository.WalletRuleRepository;
import cn.edu.tju.core.model.HttpResult;
import cn.edu.tju.core.model.ResultCodeEnum;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;

/**
 * 钱包规则管理控制器
 * 用于管理充值返点和提现手续费规则
 */
@RestController
@RequestMapping("/api/wallet-rules")
@Tag(name = "钱包规则管理", description = "管理充值返点和提现手续费规则")
public class WalletRuleController {

    @Autowired
    private WalletRuleRepository walletRuleRepository;

    /**
     * 获取所有规则
     */
    @GetMapping("")
    @Operation(summary = "获取所有规则", description = "获取所有钱包规则配置")
    public ResponseEntity<HttpResult<List<WalletRule>>> getAllRules() {
        try {
            List<WalletRule> rules = walletRuleRepository.findAll();
            return ResponseEntity.ok(HttpResult.success(rules));
        } catch (Exception e) {
            return ResponseEntity.ok(HttpResult.failure(ResultCodeEnum.SERVER_ERROR, e.getMessage()));
        }
    }

    /**
     * 根据规则类型获取规则
     */
    @GetMapping("/type/{ruleType}")
    @Operation(summary = "根据规则类型获取规则", description = "获取指定类型的所有规则（RECHARGE或WITHDRAW）")
    public ResponseEntity<HttpResult<List<WalletRule>>> getRulesByType(@PathVariable String ruleType) {
        try {
            List<WalletRule> rules = walletRuleRepository.findByRuleTypeAndIsEnabledTrueOrderByPriorityDesc(ruleType);
            return ResponseEntity.ok(HttpResult.success(rules));
        } catch (Exception e) {
            return ResponseEntity.ok(HttpResult.failure(ResultCodeEnum.SERVER_ERROR, e.getMessage()));
        }
    }

    /**
     * 获取适用于指定金额的规则
     */
    @GetMapping("/applicable/{ruleType}/{amount}")
    @Operation(summary = "获取适用规则", description = "获取适用于指定金额和类型的规则")
    public ResponseEntity<HttpResult<List<WalletRule>>> getApplicableRules(
            @PathVariable String ruleType, 
            @PathVariable BigDecimal amount) {
        try {
            List<WalletRule> rules = walletRuleRepository.findApplicableRules(ruleType, amount);
            return ResponseEntity.ok(HttpResult.success(rules));
        } catch (Exception e) {
            return ResponseEntity.ok(HttpResult.failure(ResultCodeEnum.SERVER_ERROR, e.getMessage()));
        }
    }

    /**
     * 根据ID获取规则
     */
    @GetMapping("/{id}")
    @Operation(summary = "根据ID获取规则", description = "获取指定ID的规则详情")
    public ResponseEntity<HttpResult<WalletRule>> getRuleById(@PathVariable Long id) {
        try {
            Optional<WalletRule> rule = walletRuleRepository.findById(id);
            if (rule.isPresent()) {
                return ResponseEntity.ok(HttpResult.success(rule.get()));
            } else {
                return ResponseEntity.ok(HttpResult.failure(ResultCodeEnum.NOT_FOUND, "规则不存在"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(HttpResult.failure(ResultCodeEnum.SERVER_ERROR, e.getMessage()));
        }
    }

    /**
     * 创建规则
     */
    @PostMapping("")
    @PreAuthorize("hasAuthority('ADMIN')")
    @Operation(summary = "创建规则", description = "创建新的钱包规则（仅管理员）")
    public ResponseEntity<HttpResult<WalletRule>> createRule(@RequestBody WalletRule rule) {
        try {
            WalletRule savedRule = walletRuleRepository.save(rule);
            return ResponseEntity.ok(HttpResult.success(savedRule));
        } catch (Exception e) {
            return ResponseEntity.ok(HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "创建规则失败：" + e.getMessage()));
        }
    }

    /**
     * 更新规则
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasAuthority('ADMIN')")
    @Operation(summary = "更新规则", description = "更新现有的钱包规则（仅管理员）")
    public ResponseEntity<HttpResult<WalletRule>> updateRule(
            @PathVariable Long id, 
            @RequestBody WalletRule rule) {
        try {
            Optional<WalletRule> existingRule = walletRuleRepository.findById(id);
            if (existingRule.isEmpty()) {
                return ResponseEntity.ok(HttpResult.failure(ResultCodeEnum.NOT_FOUND, "规则不存在"));
            }

            rule.setId(id);
            WalletRule updatedRule = walletRuleRepository.save(rule);
            return ResponseEntity.ok(HttpResult.success(updatedRule));
        } catch (Exception e) {
            return ResponseEntity.ok(HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "更新规则失败：" + e.getMessage()));
        }
    }

    /**
     * 启用/禁用规则
     */
    @PatchMapping("/{id}/toggle")
    @PreAuthorize("hasAuthority('ADMIN')")
    @Operation(summary = "启用/禁用规则", description = "切换规则的启用状态（仅管理员）")
    public ResponseEntity<HttpResult<WalletRule>> toggleRule(@PathVariable Long id) {
        try {
            Optional<WalletRule> ruleOpt = walletRuleRepository.findById(id);
            if (ruleOpt.isEmpty()) {
                return ResponseEntity.ok(HttpResult.failure(ResultCodeEnum.NOT_FOUND, "规则不存在"));
            }

            WalletRule rule = ruleOpt.get();
            rule.setEnabled(!rule.getEnabled());
            WalletRule updatedRule = walletRuleRepository.save(rule);
            return ResponseEntity.ok(HttpResult.success(updatedRule));
        } catch (Exception e) {
            return ResponseEntity.ok(HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "操作失败：" + e.getMessage()));
        }
    }

    /**
     * 删除规则
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('ADMIN')")
    @Operation(summary = "删除规则", description = "删除指定的钱包规则（仅管理员）")
    public ResponseEntity<HttpResult<String>> deleteRule(@PathVariable Long id) {
        try {
            if (!walletRuleRepository.existsById(id)) {
                return ResponseEntity.ok(HttpResult.failure(ResultCodeEnum.NOT_FOUND, "规则不存在"));
            }

            walletRuleRepository.deleteById(id);
            return ResponseEntity.ok(HttpResult.success("规则删除成功"));
        } catch (Exception e) {
            return ResponseEntity.ok(HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "删除规则失败：" + e.getMessage()));
        }
    }

    /**
     * 计算返点或手续费
     */
    @GetMapping("/calculate/{ruleId}/{amount}")
    @Operation(summary = "计算返点或手续费", description = "根据规则ID和金额计算返点或手续费")
    public ResponseEntity<HttpResult<BigDecimal>> calculateBonus(
            @PathVariable Long ruleId, 
            @PathVariable BigDecimal amount) {
        try {
            Optional<WalletRule> ruleOpt = walletRuleRepository.findById(ruleId);
            if (ruleOpt.isEmpty()) {
                return ResponseEntity.ok(HttpResult.failure(ResultCodeEnum.NOT_FOUND, "规则不存在"));
            }

            WalletRule rule = ruleOpt.get();
            BigDecimal bonus = rule.calculateBonus(amount);
            return ResponseEntity.ok(HttpResult.success(bonus));
        } catch (Exception e) {
            return ResponseEntity.ok(HttpResult.failure(ResultCodeEnum.SERVER_ERROR, e.getMessage()));
        }
    }
}

